<!--
 * @Author: your name
 * @Date: 2021-01-11 11:14:26
 * @LastEditTime: 2022-03-21 10:46:16
 * @LastEditors: 晟松
 * @Description: In User Settings Edit
 * @FilePath: \volunteer-vue3-admin\src\views\Login.vue
-->
<template>
    <common>
        <div class="ve_container">
            <el-card :body-style="{ background: 'rgba(0,0,0,0.15)' }">
                <h1>vue3-element-admin</h1>
                <transition name="el-fade-in-linear">
                    <el-form
                        :model="form"
                        :rules="rules"
                        v-show="!success"
                        class="ve_form"
                        ref="ref_form"
                        :inline="false"
                        @keyup.enter="onSubmit"
                    >
                        <el-form-item prop="phone">
                            <el-input v-model.trim="phone" placeholder="用户名">
                                <template #prepend>
                                    <el-icon :size="20">
                                        <Avatar />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input v-model.trim="password" show-password placeholder="密码">
                                <template #prepend>
                                    <el-icon :size="20">
                                        <Key />
                                    </el-icon>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button class="ve_submit" type="primary" @click="onSubmit">登录</el-button>
                        </el-form-item>
                    </el-form>
                </transition>
            </el-card>
            <!-- 用于测试axios在部署后，使用nginx代理跨域时出现的奇怪问题 -->
            <!-- <el-button @click="reque1">test 1</el-button>
            <el-button @click="reque2">test 2</el-button>
            <el-button @click="reque3">test 3</el-button>
            <el-button @click="reque4">test 4</el-button>
            <el-button @click="reque5">test 5</el-button>-->
        </div>
    </common>
</template>

<script>
export default {
    setup() {
        // console.log("为什么这个setup不起作用");
    },
    beforeCreate() {
        // console.log("222");
    },
    created() {
        // console.log("333");
    },
    mounted() {
        console.log("vue2 this：", this);
    },
};
</script>

<script setup>
/* eslint-disable */
import Common from "@/components/Common";
import { login } from "@/myApi/login";
import { mine, info } from "../myApi/user";
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import enums from "@/utils/enums";
import { _axios } from "@/plugins/axios";
import axios from "axios";
import { $axios, testlogin } from '@/utils/test.js'

const rules = {
    userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
};
const store = useStore();
const router = useRouter();
const form = reactive({
    phone: "13206078306",
    password: "123456",
});
const { phone, password } = toRefs(form);
const ref_form = ref(null);
const success = ref(false);

sessionStorage.clear();
store.dispatch("app/set_token", "");
store.dispatch("app/set_tag_views", []);
router.options.isAddDynamicMenuRoutes = false;

// 使用api获取到vue3组件的this
// const instance = getCurrentInstance();
// const _this = instance.appContext.config.globalProperties;
// console.log("_this: ", _this);

// onMounted(async () => {
//     let mineData = await axios.get("http://api.chengsong.info/");
//     console.log("mineData: ", mineData);
// });

// 测试发送请求
const reque1 = async () => {
    console.log('reque1: ', reque1);
    _axios.post('/login', {
        phone: phone.value,
        password: password.value,
    }, {
        headers: {
            'Content-Type': 'application/json'
        }
    }
    ).then((data) => {
        console.log('reque data: ', data);
    })
    _axios.get('/user/getAllSchoolInfo').then((data) => {
        console.log('data: ', data);

    })


}

const reque2 = async () => {
    console.log('reque2: ', reque2);
    let res = await axios.post('/api/login', {
        phone: phone.value,
        password: password.value,
    })
    console.log('res: ', res);
}

const reque3 = async () => {
    let $axios = axios.create({
        baseURL: '/api'
    })

    await $axios.request({
        url: '/login',
        method: 'post',
        data: {
            phone: "13206078306",
            password: "123456",
        }
    })
}

const reque4 = async () => {
    let $axios = axios.create({
        baseURL: '/api'
    })
    $axios.interceptors.request.use(config => {
        return config
    })

    $axios.interceptors.response.use(res => {
        return res
    })
    console.log([phone.value, password.value]);

    await $axios.request({
        url: '/login',
        method: 'post',
        data: {
            phone: phone.value,
            password: password.value,
        }
    })
}

const reque5 = async () => {
    console.log([phone.value, password.value]);


    await $axios.request({
        url: '/login',
        method: 'post',
        data: {
            phone: phone.value,
            password: password.value,
        }
    })

    await testlogin({
        phone: phone.value,
        password: password.value,
    })
}

const onSubmit = () => {
    ref_form.value.validate(async (valid) => {
        if (valid) {
            // const data = await _this.VE_API.system.login(form);
            // // 测试使用作者的api挂载是否有问题，虽然不太认可这种全局挂载行为
            // let testVE_APIData = await VE_API.user.userLoginMine();
            // console.log("testVE_APIData: ", testVE_APIData);
            // console.log("from", form, phone.value, password.value);
            let data = await login({
                phone: phone.value,
                password: password.value,
            });

            console.log("data: ", data);
            if (data.code == 200) {
                let { token, user } = data.data;
                let uname = user[user.identity].userName;
                console.log("userName: ", uname);
                let { identity } = user;

                // 注意要加上这个'Bearer '表示是哪种token
                store.dispatch("app/set_token", "Bearer " + token);
                store.dispatch("app/set_uname", uname);
                store.dispatch("app/set_identity", identity);

                // 这一步是为了获取统一格式的用户数据
                user = await info({
                    id: user[identity].id,
                    identity,
                });
                // console.log("user: ", user);
                // 注意是在这里才存入user信息
                store.dispatch("app/set_user", user.data);
                if (identity == "school") {
                    // 如果是校级管理员的话需要特别一点
                    if (user.data.managementLevel == enums["managementLevel"]["school"]) {
                        store.dispatch("app/set_school_admin", true);
                    }
                }
                success.value = true;

                // let userInfo = await mine();
                // console.log("userInfo: ", userInfo);

                router.push({ name: "AppMain" });
            }
        } else {
            return;
        }
    });
};
</script>

<style lang="scss" scoped>
.ve_container {
    position: absolute;
    z-index: 1;
    width: 400px;
    top: 50%;
    left: 100px;
    transform: translateY(-50%);
    transition: all 1s;
    min-height: 273px;
    text-align: center;
    h1 {
        font-size: 24px;
        transition: all 1s;
        font-weight: bold;
        margin-bottom: 36px;
    }
    .ve_form {
        .ve_submit {
            width: 100%;
        }
        :deep(.el-input-group__prepend) {
            padding: 0 10px;
        }
    }
}
</style>
